package com.attilax.net;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.attilax.exception.ExUtil;
import com.attilax.lang.FilterChain;
import com.attilax.lang.filterHandler;
//r13 import com.attilax.office.excelUtil;
import com.sun.image.codec.jpeg.JPEGCodec;

public class JpgFilerProcesser extends filterHandler {

	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		System.out.println("--22");
	}
	
	
	public void doFilter(Object args, FilterChain nextChain) {
		
		@SuppressWarnings("rawtypes")
		Map m=(Map) args;
		HttpServletRequest req = (HttpServletRequest) m.get("req");
		ServletResponse response=(ServletResponse) m.get("res");
		String requestURL = req.getRequestURL().toString();
		System.out.println("--22");
		 
			if (requestURL.endsWith(".jpg") && requestURL.contains("%")) {
				requestURL = requestURL.replaceAll("http://", "");
				int idx = requestURL.indexOf("/");
				String s = requestURL.substring(idx + 1); // de host n port
				int idx2 = s.indexOf("/");
				String url2 = s.substring(idx2 + 1); // de webapp
			   File file=getFile(url2);
				BufferedImage bi;
				try {
					bi = ImageIO.read(file);
				} catch (IIOException e) {
					bi = jpgRead(file);
				} catch (java.lang.IllegalArgumentException e) {
					bi = jpgRead(file);
				} catch (Exception e) {
					bi = jpgRead(file);
				}
				try {
					
					ImageIO.write(bi, "jpg", response.getOutputStream());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ExUtil.throwEx(e);
				}
				return;
			}
			  //灏嗚姹傜Щ浜ょ粰涓嬩竴涓嬭繃婊ゅ櫒锛屽鏋滆繕鏈夌殑鎯呭喌涓嬨��  
			nextChain.doFilter(m);  
	 
		
	}


	private BufferedImage jpgRead(File file)   {
		try {
			BufferedImage bi;
			com.sun.image.codec.jpeg.JPEGImageDecoder decoder = JPEGCodec
					.createJPEGDecoder(new FileInputStream(file));
			bi = decoder.decodeAsBufferedImage();
			return bi;
		} catch (Exception e) {
			e.printStackTrace();
			ExUtil.throwEx(e);
		}
		return null;
	
	}
	
	

}
